#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @Project : chat_model 
# @File    : knowledge_file_logic.py
# @IDE     : PyCharm 
# @Author  :ZH
# @Time    : 2025/1/10 16:52
__all__ = ['knowledge_file_logic']

from tortoise.expressions import Q

from apps import cruds
from apps.models import User


class KnowledgeFileLogic:
    def __init__(self):
        self.crud = cruds.knowledge_file_crud

    async def get_file_object(self, file_id, knowledge_id):
        return await self.crud.get_one(id=file_id, knowledge_id=knowledge_id, is_delete=False)

    async def check_file_object(self, knowledge_id, file_hash: str):
        return await self.crud.get_one(
            knowledge_id=knowledge_id, file_hash=file_hash, is_delete=False,
        )

    async def knowledge_file_list(self, knowledge_id, page: int = 1, limit: int = 10, name: str = None):
        skip = (page - 1) * limit
        query_sql = self.crud.model.filter(knowledge_id=knowledge_id, is_delete=False)
        if name:
            query_sql = query_sql.filter(file_name__icontains=name)
        count = await query_sql.count()
        if count:
            data = await query_sql.offset(skip).limit(limit).all()
        else:
            data = []
        return count, data

    async def all_knowledge_file(self, knowledge_id: int, user: User):
        return await self.crud.get_all(
            is_delete=False, knowledge_id=knowledge_id, user_id=user.id
        )


knowledge_file_logic = KnowledgeFileLogic()
